package cn.xmkeshe.utils.interceptor;

import cn.xmkeshe.utils.validate.ValidationRuleUtils;
import org.springframework.context.MessageSource;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;

public class ValidationInterceptor implements HandlerInterceptor {

  @Resource
  private MessageSource messageSource;

  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    boolean flag = true;
    try {
//      HandlerMethod封装关于由方法和bean组成的处理程序方法的信息。提供对方法参数、方法返回值和方法注释的方便访问。
      HandlerMethod method = (HandlerMethod) handler;
      // 拼凑验证规则名称 例如：AdminLoginController.login.rules
      String validateKey = method.getBean().getClass().getSimpleName()+"."+method.getMethod().getName()+".rules";
      System.out.println("validateKey=" + validateKey);
//      Locale.getDefault() 国际化处理
      System.out.println(this.messageSource.getMessage(validateKey,null,Locale.getDefault()));
      String validateValue = null;
      try{
        validateValue = this.messageSource.getMessage(validateKey,null,Locale.getDefault());
        if(validateValue!=null){
          String result[] = validateValue.split("\\|");
          for(int i = 0;i<result.length;i++){
            String temp[] = result[i].split(":");
            String paramName = temp[0];
            String paramValue = request.getParameter(paramName);
            System.out.println(paramName+ "=" + paramValue);
            switch (paramValue){
              case "string":{
                if(!ValidationRuleUtils.isString(paramValue)){
                  flag = false;
                }
                break;
              }
              case "int":{
                if(!ValidationRuleUtils.isInt(paramValue)){
                  flag = false;
                }
                break;
              }
              case "double":{
                if(!ValidationRuleUtils.isDouble(paramValue)){
                  flag = false;
                }
                break;
              }
              case "date":{
                if(!ValidationRuleUtils.isDate(paramValue)){
                  flag = false;
                }
                break;
              }
            }
          }
          if (flag = false){
            response.getWriter().print("isEmpty");
          }
        }
      }catch (Exception e){

      }
    } catch (Exception e) {
    }
    return flag;
  }
}
